<?php
class Core_Model_Http_Response {
	
	protected $_body = '';

	protected $_headers = array();

	protected $_httpResponseCode = 200;

	public function send() {
		$this->sendHeaders()->outputBody();
	}

	public function sendHeaders() {
		if (!$this->canSendHeaders()) return $this;
		
		$httpCodeSent = false;
		foreach($this->_headers as $name => $value) {
			if (!$httpCodeSent) {
				header($name . ': ' . $value, true, $this->_httpResponseCode);
				$httpCodeSent = true;
			} else {
				header($name . ': ' . $value);
			}
		}
		return $this;
	}

	public function outputBody() {
		echo $this->_body;
		return $this;
	}

	public function appendBody($content) {
		$this->_body .= (string)$content;
		return $this;
	}

	public function canSendHeaders($throw=false) {
		$headerAlreadySent = headers_sent($file, $line);
		if ($headerAlreadySent && $throw)
			throw new Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
		return !$headerAlreadySent;
	}

	public function setRedirect($url, $code = 302) {
		$this->setHeader('Location', $url, true)
			 ->setHttpResponseCode($code);
		return $this;
	}

	public function setHttpResponseCode($code) {
		if (!is_int($code) || (100 > $code) || (599 < $code)) {
			throw new Exception('Invalid HTTP response code');
		}
		
		$this->_httpResponseCode = $code;
		return $this;
	}
	
	public function setHeader($name, $value) {
        $name  = $this->_normalizeHeader($name);
        $value = (string) $value;
		$this->_headers[$name] = $value;
		return $this;
	}
	
	protected function _normalizeHeader($name) {
		$filtered = str_replace(array('-', '_'), ' ', (string) $name);
		$filtered = ucwords(strtolower($filtered));
		$filtered = str_replace(' ', '-', $filtered);
		return $filtered;
	}

}